package org.gukewen.service.impl;

import jakarta.annotation.Resource;
import org.gukewen.config.OrderConfig;
import org.gukewen.feign.ProductFeignClient;
import org.gukewen.order.bean.Order;
import org.gukewen.product.bean.Product;
import org.gukewen.service.OrderService;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderConfig orderConfig;
    @Resource
    DiscoveryClient discoveryClient;

    @Resource
    private LoadBalancerClient loadBalancerClient;


    @Resource
    private ProductFeignClient productFeignClient;

    @Override
    public Order createOrder(Long userId, Long productId) {
        Order order = new Order();
        order.setUserId(userId);
        order.setNickname("gukewen");
        order.setAddress("中国");
        // 使用feign客户端发送请求获取商品信息
        Product product = productFeignClient.getProductById(productId);
//        Product product = getProductById(productId);
        order.setTotalAmount(product.getPrice());
        order.setProductList(Arrays.asList( product));
        return order;
    }

    private Product getProductById(Long productId) {
        // 1.获取到商品服务所在的所有机器Ip + port
        List<ServiceInstance> instances = discoveryClient.getInstances("product-service");
        ServiceInstance instance = instances.get(0);
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        // 2.给远程发送请求
        Product product = orderConfig.restTemplate().getForObject(url, Product.class);
        return product;
    }

    private Product getProductByIdWithLoadBalancer(Long productId) {
        // 1.获取到商品服务所在的所有机器Ip + port
        ServiceInstance instance = loadBalancerClient.choose("product-service");
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        // 2.给远程发送请求
        Product product = orderConfig.restTemplate().getForObject(url, Product.class);
        return product;

    }

    private Product getProductByIdWithLoadBalancerAmotion(Long productId) {
        String url = "http://product-service/product" + productId;
        // 2.给远程发送请求 product-service会被动态替换
        Product product = orderConfig.restTemplate().getForObject(url, Product.class);
        return product;
    }


}
